package com.muqi.app.qlearn.fragments;

import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easemob.easeui.widget.CircularImage;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.pj.shops.ShopActivity;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.CustomerUtil;
import com.muqi.app.qlearn.mine.MineInfoActivity;
import com.muqi.app.qlearn.mine.MineMessageActivity;
import com.muqi.app.qlearn.mine.QrCodeCardActivity;
import com.muqi.app.qlearn.mine.SettingActivity;
import com.muqi.app.qlearn.modles.UserInfo;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.BecomeMemberActivity;
import com.muqi.app.qlearn.student.ui.FeedbackActivity;
import com.muqi.app.qlearn.student.ui.InteractiveActivity;
import com.muqi.app.qlearn.student.ui.InvitationFriendActivity;
import com.muqi.app.qlearn.student.ui.MoneyPayActivity;
import com.muqi.app.qlearn.student.ui.MyIntegralActivity;
import com.muqi.app.qlearn.student.ui.SelectChildActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.MineEntry;
import com.muqi.app.user.widget.TextProgressBar;
import com.muqi.app.user.widget.VipWindow;

public class TabMine extends BaseChildFragment implements OnClickListener {
	public static final String BroadAction = "update_user_info";
	private CircularImage avatar;
	private ImageView parentView;
	private TextView name;
	private TextView userId;
	private TextView mTogetherTv;
	private TextView mCommentTv;
	private TextView mFollowTv;

	private RelativeLayout infoBtn;
	private RelativeLayout mTogetherBtn;
	private RelativeLayout mParentBtn;
	private RelativeLayout mFansBtn;
	private RelativeLayout mFollowBtn;

	private MineEntry mScroll;
	private MineEntry mScrollMall;
	private MineEntry mBecomeMember;
	private MineEntry mMyCode;
	private MineEntry mInventFriend;
	private MineEntry mOpinion;
	private MineEntry mSetting;
	private MineEntry mMessage;

	private ImageView toMineInfo;
	private View view;
	private UserInfo userinfo;
	private UserInfoReceiver receiver;
	private TextProgressBar mProgressBar;
	private TextView mLevelOne;
	private TextView mLevelTwo;
	private TextView mParentTv;
	private TextView mFansTv;
	private ImageView mSeedOneIma;
	private ImageView mSeedTwoIma;

	private ImageView iv_vip;
	private VipWindow vipWindow;
	private ImageView vip_info;
	private UserInfo userInfo;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = LayoutInflater.from(getActivity()).inflate(
				R.layout.fragment_tab_mine, null);
		initView(view);
		if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
			if (myChildren != null && myChildren.size() > 0) {
				for (ChildBean child : myChildren) {
					if (child.child_id.equals(mSpUtil.getCurrentChildId())) {
						initChildrenDatas(child);
						break;
					}
				}
			}
		} else {
			initDatas();
		}
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		//getUserInfo();
	}

	@SuppressLint("CutPasteId")
	private void initView(View view) {
		avatar = (CircularImage) view.findViewById(R.id.mine_avatar);
		// mAvatar.setBorderWidth(0);
		// mAvatar.setBorderColor(Color.parseColor("#ffffff"));
		parentView = (ImageView) view.findViewById(R.id.mine_parents_view);

		if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
			parentView.setVisibility(View.VISIBLE);
			avatar.setOnClickListener(this);
		}
		name = (TextView) view.findViewById(R.id.mine_name);
		userId = (TextView) view.findViewById(R.id.mine_id);

		mTogetherTv = (TextView) view.findViewById(R.id.mine_praize_tv);
		mParentTv = (TextView) view.findViewById(R.id.mine_comment_tv);
		mFansTv = (TextView) view.findViewById(R.id.mine_share_tv);
		mFollowTv = (TextView) view.findViewById(R.id.mine_follow_tv);

		infoBtn = (RelativeLayout) view.findViewById(R.id.mine_info_btn);
		mTogetherBtn = (RelativeLayout) view.findViewById(R.id.mine_praize_rl);
		mParentBtn = (RelativeLayout) view.findViewById(R.id.mine_comment_rl);
		mFansBtn = (RelativeLayout) view.findViewById(R.id.mine_share_rl);
		mFollowBtn = (RelativeLayout) view.findViewById(R.id.mine_follow_rl);

		mSeedOneIma = (ImageView) view.findViewById(R.id.mine_grade_1_iv);
		mSeedTwoIma = (ImageView) view.findViewById(R.id.mine_grade_2_iv);

		mScroll = (MineEntry) view.findViewById(R.id.mine_score_rl);
		mScrollMall = (MineEntry) view.findViewById(R.id.mine_score_mall_rl);
		mBecomeMember = (MineEntry) view
				.findViewById(R.id.mine_become_member_rl);
		mMyCode = (MineEntry) view.findViewById(R.id.mine_code_rl);
		mInventFriend = (MineEntry) view
				.findViewById(R.id.mine_invent_friend_rl);
		mOpinion = (MineEntry) view.findViewById(R.id.mine_opinion_rl);
		mSetting = (MineEntry) view.findViewById(R.id.mine_setting_rl);
		toMineInfo = (ImageView) view.findViewById(R.id.to_mine_info);
		mProgressBar = (TextProgressBar) view
				.findViewById(R.id.mine_progressbar);

		mProgressBar.setProgress(80);
		mLevelOne = (TextView) view.findViewById(R.id.mine_grade_1);
		mLevelTwo = (TextView) view.findViewById(R.id.mine_grade_2);

		mMessage = (MineEntry) view.findViewById(R.id.mine_message);

		toMineInfo.setOnClickListener(this);
		infoBtn.setOnClickListener(this);
		mTogetherBtn.setOnClickListener(this);
		mParentBtn.setOnClickListener(this);
		mFansBtn.setOnClickListener(this);
		mFollowBtn.setOnClickListener(this);

		mScroll.setOnClickListener(this);
		mScrollMall.setOnClickListener(this);
		mBecomeMember.setOnClickListener(this);
		mMyCode.setOnClickListener(this);
		mInventFriend.setOnClickListener(this);
		mOpinion.setOnClickListener(this);
		mSetting.setOnClickListener(this);
		mMessage.setOnClickListener(this);

		receiver = new UserInfoReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(BroadAction);
		filter.addAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		filter.addAction(MoneyPayActivity.PAY_WITH_SUCCESS);
		getActivity().registerReceiver(receiver, filter);

		iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
		vip_info = (ImageView) view.findViewById(R.id.iv_vip_info);
		vip_info.setOnClickListener(this);

	}

	private void initDatas() {
		userinfo = CustomerUtil.getUserInfo(getActivity());
		if (userinfo != null) {
			if (userinfo.avatarInfo != null
					&& !TextUtils.isEmpty(userinfo.avatarInfo.fileurl_02)) {
				Glide.with(this).load(userinfo.avatarInfo.fileurl_02)
						.placeholder(R.drawable.default_avator).into(avatar);
			}
			name.setText(userinfo.nickname + "");

			userId.setText(mSpUtil.getClassName());
		}
	}

	private void initChildrenDatas(ChildBean myChild) {
		Glide.with(this).load(myChild.avatar_02)
				.placeholder(R.drawable.default_avator).into(avatar);
		name.setText(myChild.name + "");
		userId.setText(myChild.class_name);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.to_mine_info:
			startActivity(MineInfoActivity.class);
			break;
		case R.id.mine_score_rl:
			startActivity(MyIntegralActivity.class);
			break;
		case R.id.mine_score_mall_rl:
			startActivity(ShopActivity.class);
			break;
		case R.id.mine_become_member_rl:
			startActivity(BecomeMemberActivity.class);
			break;
		case R.id.mine_code_rl:
			startActivity(QrCodeCardActivity.class);
			break;
		case R.id.mine_invent_friend_rl:
			startActivity(InvitationFriendActivity.class);
			break;
		case R.id.mine_opinion_rl:
			startActivity(FeedbackActivity.class);
			break;
		case R.id.mine_avatar:
			// showChildrenWindow(v);
			startActivity(SelectChildActivity.class);
			break;
		case R.id.mine_setting_rl:
			startActivity(SettingActivity.class);
			break;
		case R.id.mine_follow_rl:
			Intent followIntent = new Intent(mActivity,
					InteractiveActivity.class);
			followIntent.putExtra("type", 1);
			startActivity(followIntent);
			break;
		case R.id.mine_share_rl:
			Intent fanIntent = new Intent(mActivity, InteractiveActivity.class);
			fanIntent.putExtra("type", 0);
			startActivity(fanIntent);
			break;
		case R.id.iv_vip_info:
			if (vipWindow != null) {
				vipWindow.showAsDropDown(v);
			}
			break;
		case R.id.mine_message:
			startActivity(MineMessageActivity.class);
			break;
		default:
			break;
		}
	}

	class UserInfoReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(BroadAction)) {
				initDatas();
			} else if (intent.getAction().equals(
					MContants.CHANGE_CURRENT_CHILD_ACTION)) {
				ChildBean child = (ChildBean) intent
						.getSerializableExtra(MContants.CHANGE_CURRENT_CHILD_DATAS);
				if (child != null) {
					initChildrenDatas(child);
				}
				// 重新刷新vip的信息
				getUserInfo();

			} else if (intent.getAction().equals(
					MoneyPayActivity.PAY_WITH_SUCCESS)) {
				// 重新刷新vip的信息
				getUserInfo();
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		initChildrenDatas(myChild);
		// 重新刷新vip的信息
		getUserInfo();
	}

	/**
	 * 获得用户的相关的信息
	 */
	private void getUserInfo() {

		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("user_id", mSpUtil.getCurrentChildId());

		String requestUrl = ParamsUtils.buildParams(NetWorkApi.GET_USER_INFO,
				sendMap);
		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				Log.e("===", result);
				if (resuleCode == RESULTCODE.SUCCESS) {
					userInfo = ResponseUtils.getUserInfo(mActivity, result);
					if (userInfo != null) {
						mFansTv.setText(userInfo.fans);
						mFollowTv.setText(userInfo.follow);
						mParentTv.setText((int) Float
								.parseFloat(userInfo.peibancount) + "");
						mTogetherTv.setText((int) Float
								.parseFloat(userInfo.multiple_total) + "");
						if (userInfo.type != null && !userInfo.type.equals("")) {
							vip_info.setVisibility(View.VISIBLE);
							if (vipWindow == null) {
								vipWindow = new VipWindow(mActivity);
							}
							vipWindow.setTime(userInfo.expiry_end_date);
							if ("base".equals(userInfo.type)) {
								iv_vip.setImageResource(R.drawable.vip_base);
							} else {
								iv_vip.setImageResource(R.drawable.vip_follows);
							}
						} else {
							iv_vip.setVisibility(View.INVISIBLE);
							vip_info.setVisibility(View.GONE);
							vipWindow = null;
							vip_info.setImageDrawable(null);
						}
					}
				}

			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		getUserInfo();
	}
	

}
